package com.atkxp.sys.filter;

import com.alibaba.fastjson2.JSON;
import com.atkxp.sys.entity.LoginUser;
import com.atkxp.sys.entity.Result;
import com.atkxp.sys.entity.User;
import com.atkxp.sys.utils.JwtUtils;
import com.atkxp.sys.utils.RedisCache;
import com.atkxp.sys.utils.RedisUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author longhunpomie
 * @declaration
 * @email 3314028177@qq.com
 * @create 2023/9/13-18:32
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        String token = httpServletRequest.getHeader("X-Token");

        if(!StringUtils.hasText(token)) {
//            httpServletResponse.getWriter().write(JSON.toJSONString(Result.fail(20003,"jwt令牌无效，请重新登录")));
            filterChain.doFilter(httpServletRequest, httpServletResponse);
            return;
        }

        LoginUser loginUser = redisCache.getCacheObject(token);

//        if(loginUser == null) {
//            throw new AccountExpiredException("jwt已过期，请重新登录");
//        }

        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = null;
        try {
            usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);

            filterChain.doFilter(httpServletRequest, httpServletResponse);
        } catch (NullPointerException e) {
            throw new AuthenticationCredentialsNotFoundException("jwt已过期，请重新登录");
        }
    }
}
